package com.zhuangjie.xxljob.config;

import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import com.zhuangjie.xxljob.properties.XxlJobProperties;
import com.zhuangjie.xxljob.utils.MathUtils;
import com.zhuangjie.xxljob.utils.PortChecker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
@EnableConfigurationProperties(XxlJobProperties.class)
public class XxlJobConfig {
    @Value("${server.port}")
    private Integer projectPort;

    @Value("${spring.application.name}")
    private String appName;

    /**
     * 默认的projectPort
     */
    private static final int DEFAULT_PORT = 8080;




    public int dynamicAcquisitionPort(Integer port) throws Exception {
        if (port != null)  return port;
        // 如果没有定义，那根据当前项目，"向前获取"
        if (projectPort == null) {
            projectPort = DEFAULT_PORT;
        }
        log.info("xxl-job log: project port is"+projectPort);
        for (int currentPort = MathUtils.getMinimumLevelNumber(projectPort) - 1; currentPort >= 0; currentPort--) {
            if (PortChecker.isPortAvailable(currentPort)) {
                log.info("xxl-job log: xxl-job used port is {}",currentPort);
                return currentPort;
            }
        }
        throw new Exception("无法为xxl-job分配动态端口！");
    }

    /**
     * 动态获取appName
     * @param appName
     * @return
     * @throws Exception
     */
    public String dynamicAcquisitionAppName(String appName) throws Exception {
        if (appName != null) return appName;
        if (this.appName != null) {
            log.info("xxl-job used appName is {}",this.appName);
            return this.appName;
        }
        throw new Exception("无法为xxl-job动态分配appName！");
    }

    @Bean
    public XxlJobSpringExecutor xxlJobExecutor(XxlJobProperties xxlJobProperties) throws Exception {
        log.info(">>>>>>>>>>> xxl-job config init.");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        xxlJobSpringExecutor.setAdminAddresses(xxlJobProperties.getAdmin().getAddresses());
        xxlJobSpringExecutor.setAppname(dynamicAcquisitionAppName(xxlJobProperties.getExecutor().getAppname()));
        xxlJobSpringExecutor.setIp(xxlJobProperties.getExecutor().getIp());
        xxlJobSpringExecutor.setPort(dynamicAcquisitionPort(xxlJobProperties.getExecutor().getPort()));
        xxlJobSpringExecutor.setAccessToken(xxlJobProperties.getAccessToken());
        xxlJobSpringExecutor.setLogPath(xxlJobProperties.getExecutor().getLogpath());
        xxlJobSpringExecutor.setLogRetentionDays(xxlJobProperties.getExecutor().getLogretentiondays());
        return xxlJobSpringExecutor;
    }
}
